package com.dwxt.cdms.service;

import cn.binarywang.tools.generator.ChineseIDCardNumberGenerator;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dwxt.cdms.api.common.utils.StringUtil;
import com.dwxt.cdms.applets.dto.IndexGraphDayResDTO;
import com.dwxt.cdms.applets.dto.IndexGraphResDTO;
import com.dwxt.cdms.applets.dto.IndexReqDTO;
import com.dwxt.cdms.base.Page;
import com.dwxt.cdms.constant.EquipCategory;
import com.dwxt.cdms.constant.ReceiveDataType;
import com.dwxt.cdms.dao.*;
import com.dwxt.cdms.entity.*;
import com.dwxt.cdms.entity.laibang.*;
import com.dwxt.cdms.util.*;
import com.dwxt.cdms.view.wristwatch.NewSleepDataView;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.util.HttpUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class LbWatchService {
    //    private final String prefix = "https://nbtest.lonbon.com/locationCare";
    public boolean startSendHeart = false;

    @Value("${lb.appid}")
    private String appid;

    @Value("${lb.secret}")
    private String secretStr;

    @Value("${lb.prefix}")
    private String prefix;

    @Value("${lb.communityId}")
    private String communityId;

    @Value("${lb.buildingId}")
    private String buildingId;

    @Value("${lb.careLevelId}")
    private String careLevelId;

    @Autowired
    private LbWatchMapper lbWatchMapper;
    @Autowired
    private StationService stationService;
    @Autowired
    private ElectronicFenceService electronicFenceService;
    @Autowired
    private LbWatchStepMapper lbWatchStepMapper;
    @Autowired
    private LbWatchSleepMapper lbWatchSleepMapper;
    @Autowired
    private LbWatchDataMapper lbWatchDataMapper;
    @Autowired
    private EquipmentCustomMapper equipmentCustomMapper;

    public BaseResult page(Page page, Integer customerId, String name, String type, String category) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        LbWatchExample example = new LbWatchExample();
        LbWatchExample.Criteria criteria = example.createCriteria();
        example.setOrderByClause("create_time desc");
        if (customerId != null) {
            criteria.andCustomer_idEqualTo(customerId);
        }
        List<LbWatch> lbWatchList = lbWatchMapper.selectByExample(example);
        List<LbWatchVO> lbWatchVOList = new ArrayList<>();
        for (LbWatch lbWatchVO2 : lbWatchList) {
            //组装数据
            LbWatchVO lbWatchVO = VO2Entity(lbWatchVO2);
            lbWatchVOList.add(lbWatchVO);
        }
        PageInfo pageInfo = new PageInfo(lbWatchList);
        return BaseResult.ok(pageInfo);
    }

    public BaseResult list() {
        LbWatchExample example = new LbWatchExample();
        example.setOrderByClause("create_time desc");
        List<LbWatch> lbWatchList = lbWatchMapper.selectByExample(example);
        return BaseResult.ok(lbWatchList);
    }

    public BaseResult add(LbWatch lbWatch) {
        lbWatchMapper.insertSelective(lbWatch);
        return BaseResult.ok();
    }

    public BaseResult delete(Integer id) {
        lbWatchMapper.deleteByPrimaryKey(id);
        return BaseResult.ok();
    }

    public BaseResult update(LbWatch id) {
        lbWatchMapper.updateByPrimaryKeySelective(id);
        return BaseResult.ok();
    }

    public LbWatch getLbWatchById(Integer id) {
        return lbWatchMapper.selectByPrimaryKey(id);
    }

    public BaseResult pageGroup(Page page, String name, String type, String category) {
        Integer stationId = stationService.getLoginUserStation();
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        if (EquipCategory.LB.equals(category)) {
            if (ReceiveDataType.HEARTBEAT.equals(type)) {
                List<LbWatchVO2> lbWatchVO2List = lbWatchMapper.selectGroup(name, stationId);
                List<LbWatchVO> lbWatchVOList = new ArrayList<>();
                for (LbWatchVO2 lbWatchVO2 : lbWatchVO2List) {
                    //组装数据
                    LbWatchVO lbWatchVO = VO22Entity(lbWatchVO2);
                    lbWatchVOList.add(lbWatchVO);
                }
                PageInfo pageInfo = new PageInfo(lbWatchVOList);
                return BaseResult.ok(pageInfo);
            }
        }
        return BaseResult.build(StatusCode.PARAMETER_WRONG);
    }

    /**
     * 数据组装
     *
     * @param vo
     * @return
     */
    private LbWatchVO VO22Entity(LbWatch vo) {
        LbWatchVO entity = new LbWatchVO();
        BeanUtils.copyProperties(vo, entity);
        entity.setAddAmbientBeaconDTO(JSON.parse(vo.getAddAmbientBeaconDTO()));
        entity.setAddBodyTemperatureDTO(JSON.parse(vo.getAddBodyTemperatureDTO()));
        entity.setAddDevicePowerDTOList(JSON.parseArray(vo.getAddDevicePowerDTOList()));
        entity.setAddHealthDTO(JSON.toJavaObject(JSON.parseObject(vo.getAddHealthDTO()), AddHealthDTO.class));
        entity.setAddHumitureDTO(JSON.parse(vo.getAddHumitureDTO()));
        entity.setAddPositionStatusDTOList(JSON.parseArray(vo.getAddPositionStatusDTOList(), AddPositionStatusDTO.class));
        entity.setAddSignalQualityDTO(JSON.toJavaObject(JSON.parseObject(vo.getAddSignalQualityDTO()), AddSignalQualityDTO.class));
        entity.setAddWearStatusDTO(JSON.toJavaObject(JSON.parseObject(vo.getAddWearStatusDTO()), AddWearStatusDTO.class));
        entity.setAddWifiDTO(JSON.toJavaObject(JSON.parseObject(vo.getAddWifiDTO()), AddWifiDTO.class));
        return entity;
    }

    /**
     * 数据组装
     *
     * @param vo
     * @return
     */
    private LbWatchVO VO2Entity(LbWatch vo) {
        LbWatchVO entity = new LbWatchVO();
        BeanUtils.copyProperties(vo, entity);
        entity.setAddAmbientBeaconDTO(JSON.parse(vo.getAddAmbientBeaconDTO()));
        entity.setAddBodyTemperatureDTO(JSON.parse(vo.getAddBodyTemperatureDTO()));
        entity.setAddDevicePowerDTOList(JSON.parseArray(vo.getAddDevicePowerDTOList()));
        entity.setAddHealthDTO(JSON.toJavaObject(JSON.parseObject(vo.getAddHealthDTO()), AddHealthDTO.class));
        entity.setAddHumitureDTO(JSON.parse(vo.getAddHumitureDTO()));
        entity.setAddPositionStatusDTOList(JSON.parseArray(vo.getAddPositionStatusDTOList(), AddPositionStatusDTO.class));
        entity.setAddSignalQualityDTO(JSON.toJavaObject(JSON.parseObject(vo.getAddSignalQualityDTO()), AddSignalQualityDTO.class));
        entity.setAddWearStatusDTO(JSON.toJavaObject(JSON.parseObject(vo.getAddWearStatusDTO()), AddWearStatusDTO.class));
        entity.setAddWifiDTO(JSON.toJavaObject(JSON.parseObject(vo.getAddWifiDTO()), AddWifiDTO.class));
        return entity;
    }


    /**
     * @Description:获取来邦token
     * @Param []
     * @Return java.lang.String
     * @Author chendq
     * @Date 2021/12/27
     **/
    public String getLaiBangToken() {
        //如果redis中没有则重新获取
        String laibangToken = RedisUtil.get("laiBangToken", String.class);
        if (StringUtil.isNotBlank(laibangToken)) {
            return laibangToken;
        }
        //String appid = "7ad7707747284b1182a814ab298957a7";
        //String secretStr = "058e59929f5";
        /*appid = "2da601f102714750a53d95e43822d7a2";
        secretStr = "82ad526a79c";*/
        String url = prefix + "/api/v1.0/org/app/token";
        String secret = MD5Util.MD5EncodeUtf8(secretStr);
        secret = MD5Util.MD5EncodeUtf8(secret + "nb_lbhf");
        secret = SecretUtil.encode(secret);
        HashMap<String, Object> params = new HashMap<>();
        params.put("appId", appid);
        params.put("appSecret", secret);
        String res = HttpUtils.postRequest(url, params);
        JSONObject resObj = JSON.parseObject(res);
        JSONObject body = (JSONObject) resObj.get("body");
        String token = body.get("token").toString();
        RedisUtil.set("laiBangToken", token, 3600l);
        return token;
    }


    //添加房间和床位
    public Map addAreaAndBed() {
        //创建房间
        String areaUrl = prefix + "/api/v1.0/personManager/orgArea/area";
        HashMap<String, Object> params = new HashMap<>();
        HashMap<String, String> headers = new HashMap<>();
        headers.put("token", getLaiBangToken());
        params.put("communityId", communityId);
        params.put("buildingId", buildingId);
        params.put("areaName", UUIDUtil.getUUID());
        String res = HttpUtils.postRequest(areaUrl, headers, params);
        JSONObject body = (JSONObject) JSON.parseObject(res).get("body");
        String areaId = (String) body.get("areaId");
        //创建床位
        String bedUrl = prefix + "/api/v1.0/personManager/orgArea/bed";
        params.put("areaId", areaId);
        params.put("bedName", UUIDUtil.getUUID());
        String bedRes = HttpUtils.postRequest(bedUrl, headers, params);
        JSONObject bedBody = (JSONObject) JSON.parseObject(bedRes).get("body");
        String bedId = (String) bedBody.get("bedId");
        params.put("bedId", bedId);
        return params;
    }

    //添加绑定老人
    public String addElder(String bandCode) {
        //创建房间
        String addElderUrl = prefix + "/api/v1.0/thirdParty/elder";
        HashMap<String, Object> params = new HashMap<>();
        HashMap<String, String> headers = new HashMap<>();
        headers.put("token", getLaiBangToken());
        //老人信息
        HashMap<String, Object> elderData = new HashMap<>();
        elderData.put("name", "安博馨");
        elderData.put("identity", ChineseIDCardNumberGenerator.getInstance().generate());
        elderData.put("gender", 1);
        elderData.put("phoneNum", "18888888888");
        elderData.put("careLevelId", careLevelId);
        elderData.put("checkInTime", "2022-01-01 00:00:00");
        elderData.put("checkInNum", UUIDUtil.getUUID());
        elderData.put("birthday", "2022-01-01");
        elderData.put("nursingWorkerId", "");
        elderData.put("medicalHistory", "");
        elderData.put("careInstructionOne", "");
        elderData.put("careInstructionTwo", "");
        elderData.put("careInstructionThree", "");
        elderData.put("careInstructionFour", "");
        elderData.put("address", "中国重庆");
        elderData.put("careObjectId", "");
        elderData.put("region", "");
        elderData.put("telephone", "");
        elderData.put("doctorId", "");
        elderData.put("careinfoId", "");

        //机构房间信息
        Map orgArea = addAreaAndBed();
        //绑定手环设备信息
        LbWatchCodeTool parse = LbWatchCodeTool.parse(bandCode);
        HashMap band = new HashMap();
        band.put("imei", parse.getImei());
        band.put("mac", parse.getMac());
        band.put("electricityMode", parse.getCardMode());
        band.put("hardwareVersion", parse.getDeviceName());
        band.put("deviceIterationNumber", parse.getGeneration());
        //家人联系方式
        ArrayList<Map> contactsList = new ArrayList<>();
        HashMap<String, Object> contact = new HashMap<>();
        contact.put("name", "联系人");
        contact.put("phoneNum", "18888888888");
        contact.put("relationDesc", "本人");
        contactsList.add(contact);
        //紧急救助人
        ArrayList<Map> emergencyList = new ArrayList<>();
        HashMap<String, Object> emergency = new HashMap<>();
        emergency.put("contactsName", "紧急救助人");
        emergency.put("contactsPhone", "18888888888");
        emergency.put("contactsRelation", "本人");
        emergencyList.add(emergency);
        String elderDataStr = JSON.toJSONString(elderData);
        String orgAreaStr = JSON.toJSONString(orgArea);
        String bandStr = JSON.toJSONString(band);
        String contactsListStr = JSON.toJSONString(contactsList);
        String emergencyListStr = JSON.toJSONString(emergencyList);
        params.put("elderData", elderDataStr);
        params.put("orgArea", orgAreaStr);
        params.put("band", bandStr);
        params.put("contactsList", contactsListStr);
        params.put("emergencyList", emergencyListStr);
        String res = HttpUtils.postRequest(addElderUrl, headers, params);
        log.error("添加老人返回信息：" + res);
        log.error("参数：" + params);
        try {
            JSONObject jsonObject = JSON.parseObject(res);
            if (jsonObject.get("status").equals("200")) {
                return (String) jsonObject.get("body");
            }
        } catch (Exception e) {
            log.error("来邦添加绑定老人失败：失败请求信息：" + params.toString() + "。失败返回信息：" + res + "。请求地址：" + addElderUrl);
        }
        return "error";
    }


    /**
     * @Description: 开启查找长者
     * @Param [lbUserid]
     * @Return void
     * @Author chendq
     * @Date 2021/12/28
     **/
    public void openFindElder(String lbUserid) {
        String url = prefix + "/api/v1.0/thirdParty/realTimeTrack";
        HashMap<String, Object> params = new HashMap<>();
        HashMap<String, String> headers = new HashMap<>();
        headers.put("token", getLaiBangToken());
        params.put("careObjectId", lbUserid);
        params.put("actionType", 1);
        String res = HttpUtils.postRequest(url, headers, params);
        JSONObject jsonObject = JSON.parseObject(res);
        if (!jsonObject.get("status").equals("200")) {
            log.error("来邦手表开启查找长者失败！失败请求参数：" + params + "。返回结果：" + res);
        }

    }

    /**
     * @Description: 查询轨迹
     * @Param []
     * @Return void
     * @Author chendq
     * @Date 2021/12/28
     **/
    public LbWatchLoc getTrackList(String lbUserId) {
        String url = prefix + "/api/v1.0/thirdParty/realTimeTrackMap";
        HashMap<String, Object> params = new HashMap<>();
        HashMap<String, String> headers = new HashMap<>();
        headers.put("token", getLaiBangToken());
        params.put("careObjectId", lbUserId);
        params.put("currentPage", 1);
        params.put("pageSize", 999);
        String res = HttpUtils.getRequest(url, headers, params);
        JSONObject body = (JSONObject) JSON.parseObject(res).get("body");
        List<Map> list = (List) body.get("list");
        Map map = list.get(list.size() - 1);
        LbWatchLoc lbWatchLoc = JSON.parseObject(JSON.toJSONString(map), LbWatchLoc.class);
        lbWatchLoc.setCreateTime(new Date());
        long time = Long.valueOf(map.get("time").toString()) * 1000l;
        lbWatchLoc.setReportTime(new Date(time));
        double[] doubles = GpsUtils.bd09togcj02(Double.valueOf(lbWatchLoc.getLgt()), Double.valueOf(lbWatchLoc.getLat()));
        lbWatchLoc.setLat(String.valueOf(doubles[1]));
        lbWatchLoc.setLgt(String.valueOf(doubles[0]));
        return lbWatchLoc;
    }

    /**
     * @Description: 根据来邦userid更新步数
     * @Param [lbUserId, mac, customerId]
     * @Return void
     * @Author chendq
     * @Date 2021/12/28
     **/
    public void insertStep(String lbUserId, String mac, Integer customerId) {
        String url = prefix + "/api/v1.0/thirdParty/elderSteps";
        HashMap<String, Object> params = new HashMap<>();
        HashMap<String, String> headers = new HashMap<>();
        headers.put("token", getLaiBangToken());
        params.put("careObjectId", lbUserId);
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH) - 1, 0, 0, 0);
        long startTime = calendar.getTime().getTime() / 1000;
        Calendar calendar1 = Calendar.getInstance();
        calendar1.set(calendar1.get(Calendar.YEAR), calendar1.get(Calendar.MONTH), calendar1.get(Calendar.DAY_OF_MONTH) - 1, 23, 59, 59);
        long endTime = calendar1.getTime().getTime() / 1000;
        params.put("startTime", startTime);
        params.put("endTime", endTime);
        String res = HttpUtils.getRequest(url, headers, params);
        JSONObject body = (JSONObject) JSON.parseObject(res).get("body");
        List<Map> list = (List) body.get("list");
        if (list != null && list.size() > 0) {
            Map map = list.get(0);
            LbWatchStep step = new LbWatchStep();
            step.setStepsNumber((Integer) map.get("stepsNumber"));
            step.setRecordTime(new Date((Integer) map.get("recordTime") * 1000l));
            step.setDeviceMac(mac);
            step.setCustomerId(customerId);
            lbWatchStepMapper.insertSelective(step);
        }
    }


    public void insertSleep(String lbUserId, String mac, Integer customerId) {
        String url = prefix + "/api/v1.0/dataStatistics/elderSleep";
        HashMap<String, Object> params = new HashMap<>();
        HashMap<String, String> headers = new HashMap<>();
        headers.put("token", getLaiBangToken());
        params.put("careObjectId", lbUserId);
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH) - 1, 12, 0, 0);
        long startTime = calendar.getTime().getTime() / 1000;
        System.out.println(new Date(calendar.getTime().getTime()));
        params.put("startTime", startTime);
        params.put("dayType", 2);
        String res = HttpUtils.getRequest(url, headers, params);
        JSONObject body = (JSONObject) JSON.parseObject(res).get("body");
        if (body.get("sleep") != null) {
            LbWatchSleep sleep = JSON.parseObject(body.get("sleep").toString(), LbWatchSleep.class);
            sleep.setDeepSleep(sleep.getDeepSleep() / 60);
            sleep.setShallowSleep(sleep.getShallowSleep() / 60);
            sleep.setSoberSleep(sleep.getSoberSleep() / 60);
            sleep.setCustomerId(customerId);
            sleep.setDeviceMac(mac);
            lbWatchSleepMapper.insertSelective(sleep);
        }
    }

    public List<IndexGraphDayResDTO> selectGraphWithDay(IndexReqDTO indexReqDTO) {
        if (indexReqDTO.getType().equals(ReceiveDataType.HEARTBEAT)) {
            //心率
            return lbWatchDataMapper.selectGraphHeartbeatWithDay(indexReqDTO);
        } else if (indexReqDTO.getType().equals(ReceiveDataType.BLOOD_OXYGEN)) {
            //血氧
            return lbWatchDataMapper.selectGraphOxygenWithDay(indexReqDTO);
        } else if (indexReqDTO.getType().equals(ReceiveDataType.BLOOD_PRESSURE)) {
            //血压
            return lbWatchDataMapper.selectGraphPressureWithDay(indexReqDTO);
        } else if (indexReqDTO.getType().equals(ReceiveDataType.STEP)) {
            //计步
            return lbWatchStepMapper.selectGraphStepWithDay(indexReqDTO);
        }
        return null;
    }

    public NewSleepDataView getDaySleepByTimeAndCustomerId(Integer customerId, String startTime) {
        NewSleepDataView newSleepDataView = lbWatchSleepMapper.getDaySleepByTimeAndCustomerId(customerId, startTime);
        return newSleepDataView;
    }

    public List<NewSleepDataView> selectGraphLbSleepWeekOrMonth(IndexReqDTO indexReqDTO) {
        return lbWatchSleepMapper.selectGraphLbSleepWeekOrMonth(indexReqDTO);

    }

    public List<NewSleepDataView> selectGraphLbSleepYear(IndexReqDTO indexReqDTO) {
        return lbWatchSleepMapper.selectGraphLbSleepYear(indexReqDTO);
    }

    public List<IndexGraphResDTO> selectGraphData(IndexReqDTO indexReqDTO) {
        if (ReceiveDataType.BLOOD_OXYGEN.equals(indexReqDTO.getType())) {
            indexReqDTO.setField("bloodOxygen");
            return lbWatchDataMapper.selectGraphData(indexReqDTO);
        } else if (ReceiveDataType.HEARTBEAT.equals(indexReqDTO.getType())) {
            indexReqDTO.setField("heartRate");
            return lbWatchDataMapper.selectGraphData(indexReqDTO);
        } else if (ReceiveDataType.BLOOD_PRESSURE.equals(indexReqDTO.getType())) {
            return lbWatchDataMapper.selectGraphPressureData(indexReqDTO);
        } else if (ReceiveDataType.STEP.equals(indexReqDTO.getType())) {
            return lbWatchStepMapper.selectGraphData(indexReqDTO);
        }
        return null;
    }

    public List<IndexGraphResDTO> selectStepGraphData(IndexReqDTO indexReqDTO) {
        return lbWatchStepMapper.selectGraphData(indexReqDTO);
    }

    public void updateElder(String lbUserid, Customer customer) {
        //根据来邦userid查询长者
        String url = prefix + "/api/v1.0/personManager/elder";
        HashMap<String, Object> params = new HashMap<>();
        HashMap<String, String> headers = new HashMap<>();
        headers.put("token", getLaiBangToken());
        params.put("careObjectId", lbUserid);
        String res = HttpUtils.getRequest(url, headers, params);
        JSONObject body = (JSONObject) JSON.parseObject(res).get("body");
        JSONArray data = (JSONArray) body.get("data");
        Map map = JSON.parseObject(JSON.toJSONString(data.get(0)), Map.class);
        //修改长者姓名电话
        String updateUrl = prefix + "/api/v1.0/thirdParty/elder";
        HashMap<String, Object> params1 = new HashMap<>();
        //老人信息
        HashMap<String, Object> elderData = new HashMap<>();
        elderData.put("name", customer.getName());
        elderData.put("careObjectId", map.get("careObjectId"));
        elderData.put("identity", ChineseIDCardNumberGenerator.getInstance().generate());
        elderData.put("gender", 1);
        elderData.put("phoneNum", customer.getPhone());
        elderData.put("careLevelId", "135414333806765755");
        elderData.put("checkInTime", "2022-01-01 00:00:00");
        elderData.put("checkInNum", map.get("checkInNum"));
        elderData.put("birthday", "2022-01-01");
        elderData.put("nursingWorkerId", "");
        elderData.put("medicalHistory", "");
        elderData.put("careInstructionOne", "");
        elderData.put("careInstructionTwo", "");
        elderData.put("careInstructionThree", "");
        elderData.put("careInstructionFour", "");
        elderData.put("address", "");
        elderData.put("region", "");
        elderData.put("telephone", "");
        elderData.put("doctorId", "");
        elderData.put("careinfoId", map.get("careinfoId"));

        //机构房间信息
        Map orgArea = JSON.parseObject(JSON.toJSONString(map.get("orgArea")), Map.class);
        //绑定手环设备信息
        Map band = JSON.parseObject(JSON.toJSONString(map.get("band")), Map.class);
        //家人联系方式
        ArrayList<Map> contactsList = new ArrayList<>();
        HashMap<String, Object> contact = new HashMap<>();
        contact.put("name", customer.getName());
        contact.put("phoneNum", customer.getPhone());
        contact.put("relationDesc", "本人");
        contactsList.add(contact);
        //紧急救助人
        ArrayList<Map> emergencyList = new ArrayList<>();
        HashMap<String, Object> emergency = new HashMap<>();
        emergency.put("contactsName", "紧急救助人");
        emergency.put("contactsPhone", customer.getPhone());
        emergency.put("contactsRelation", "本人");
        emergencyList.add(emergency);
        String elderDataStr = JSON.toJSONString(elderData);
        String orgAreaStr = JSON.toJSONString(orgArea);
        String bandStr = JSON.toJSONString(band);
        String contactsListStr = JSON.toJSONString(contactsList);
        String emergencyListStr = JSON.toJSONString(emergencyList);
        params1.put("elderData", elderDataStr);
        params1.put("orgArea", orgAreaStr);
        params1.put("band", bandStr);
        params1.put("contactsList", contactsListStr);
        params1.put("emergencyList", emergencyListStr);
        String result = HttpUtils.putRequest(updateUrl, headers, params1);
        log.info("发放来邦手表修改长者返回结果" + result + "。请求信息：" + params1);
    }

    /**
     * @Description: 添加用药提醒
     * @Param [careObjectId]
     * @Return java.lang.String
     * @Author chendq
     * @Date 2022/3/4
     **/
    public String addRemind( String careObjectId,Integer hour, Integer minute) {

        String url = prefix + "/api/v1.0/thirdParty/band/remind";
        HashMap<String, String> headers = new HashMap<>();
        headers.put("token", getLaiBangToken());
        HashMap<String, Object> params = new HashMap<>();
        params.put("careObjectId", careObjectId);
        params.put("hourNum", hour);
        params.put("minuteNum", minute);
        String res = HttpUtils.postRequest(url, headers, params);
        log.info("添加来邦用药提醒。careObjectId:" + careObjectId + "。返回结果：" + res);
        JSONObject resObj = JSON.parseObject(res);
        return resObj.get("body").toString();

    }


    /**
     * @Description: 删除来邦用药提醒
     * @Param [careObjectId, taskId]
     * @Return void
     * @Author chendq
     * @Date 2022/3/4
     **/
    public String deleteRemind(String careObjectId, String taskId) {
        String url = prefix + "/api/v1.0/thirdParty/band/remind/delete";
        HashMap<String, String> headers = new HashMap<>();
        headers.put("token", getLaiBangToken());
        HashMap<String, Object> params = new HashMap<>();
        params.put("careObjectId", careObjectId);
        params.put("taskId", taskId);
        String res = HttpUtils.postRequest(url, headers, params);
        JSONObject resObj = JSON.parseObject(res);
        log.info("删除来邦用药提醒。careObjectId:" + careObjectId + "；taskId:" + taskId + "。返回结果：" + res);
        if (resObj.get("status").equals("200")) {
            return resObj.get("body").toString();
        }
        return resObj.toJSONString();
    }

    /**
     * @Description: 修改用药提醒
     * @Param [careObjectId, taskId, hourNum, minuteNum]
     * @Return java.lang.String
     * @Author chendq
     * @Date 2022/3/4
     **/
    public String updateRemind(String careObjectId, String taskId, Integer hourNum, Integer minuteNum) {
        String url = prefix + "/api/v1.0/thirdParty/band/remind";
        HashMap<String, String> headers = new HashMap<>();
        headers.put("token", getLaiBangToken());
        HashMap<String, Object> params = new HashMap<>();
        params.put("careObjectId", careObjectId);
        params.put("taskId", taskId);
        params.put("hourNum", hourNum);
        params.put("minuteNum", minuteNum);
        String res = HttpUtils.putRequest(url, headers, params);
        log.info("修改来邦用药提醒。careObjectId:" + careObjectId + "；taskId:" + taskId + "。返回结果：" + res);
        JSONObject resObj = JSON.parseObject(res);
        if (resObj.get("status").equals("200")) {
            return resObj.get("body").toString();
        }
        return null;
    }

    /**
     * @Description: 查询用药提醒
     * @Param [careObjectId]
     * @Return java.util.List
     * @Author chendq
     * @Date 2022/3/4
     **/
    public List<Map> getRemindList(String careObjectId) {
        String url = prefix + "/api/v1.0/thirdParty/band/remind";
        HashMap<String, String> headers = new HashMap<>();
        headers.put("token", getLaiBangToken());
        HashMap<String, Object> params = new HashMap<>();
        params.put("careObjectId", careObjectId);
        String res = HttpUtils.getRequest(url, headers, params);
        JSONObject resObj = JSON.parseObject(res);
        if (resObj.get("status").equals("200")) {
            List<Map>  list = JSON.parseObject(JSON.parseObject(resObj.get("body").toString()).get("data").toString(), List.class);
            return list;
        }
        return null;
    }


    public BaseResult selectRemindList(Integer customerId) {
        String lbUserid = equipmentCustomMapper.selectLbUseridByCustomerId(customerId);
        List<Map> remindList = this.getRemindList(lbUserid);
        return BaseResult.ok(remindList);
    }

    public BaseResult deleteRemindByCustomerIdAndTaskId(Integer customerId, String taskId) {
        String lbUserid = equipmentCustomMapper.selectLbUseridByCustomerId(customerId);
        return BaseResult.ok(this.deleteRemind(lbUserid, taskId));
    }
}
